﻿using System;
using System.Timers;
using System.ComponentModel;

namespace AsynchRequest
{
    public class RequestAsynchWithTimer : Request
    {
        Timer _timer;

        public RequestAsynchWithTimer(double interval, Action action)
            : base(action)
        {
            _timer = new Timer()
            {
                Interval = interval
            };
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler((s, ea) =>
            {
                _timer.Enabled = true;
                _timer.Start();
            });
            _timer.Elapsed += new ElapsedEventHandler((s, ea) =>
            {
                _timer.Enabled = false;
                _timer.Stop();
                if (!bgw.IsBusy)
                    bgw.RunWorkerAsync();
            });
        }

        public void Start()
        {
            _timer.Enabled = true;
            _timer.Start();

        }

        public void Stop()
        {
            _timer.Enabled = false;
            bgw.CancelAsync();
            _timer.Stop();
        }

    }
}
